package com.company.project.search.engine;

import com.company.project.search.cache.DataBaseCache;
import com.company.project.search.cache.MemoryCache;
import com.company.project.search.interfaces.ISearch;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 爬虫入口，数据回调
 */
public class Inlets implements ISearch, ICallBack {
    public static final ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();

    public static ISearch getInstance() {
        return Holder.ins;
    }

    public static final int MAX = 10240;
    public static AtomicInteger curSize = new AtomicInteger(0);

    @Override
    public void search(@NotNull Param p, @NotNull AbstractE... search) {
        for (AbstractE engine : search) {
            curSize.addAndGet(1);
            engine.search(p);
        }
    }

    /**
     * 网站数据爬完回调
     */
    @Override
    public void callback(Result result) {
        curSize.addAndGet(-1);
        MemoryCache.saveMemory(result); // 更新本地缓存
        // TODO 判空处理
        DataBaseCache.save(result.list); // 更新数据库
    }


    public static final Runnable runnable = () -> {
        curSize.set(MAX / 3);
        MemoryCache.gc();
    };


    private static final class Holder {
        private static final Inlets ins = new Inlets();
    }

    private Inlets() {
        schedule.scheduleWithFixedDelay(runnable, 30, 30, TimeUnit.SECONDS);
        E1.getInstance().setCacheCallBack(this);
        E2.getInstance().setCacheCallBack(this);
        E3.getInstance().setCacheCallBack(this);
        E4.getInstance().setCacheCallBack(this);
        E5.getInstance().setCacheCallBack(this);
        E6.getInstance().setCacheCallBack(this);
    }
}
